package com.junlong0716.enjoylearning.ui

import android.Manifest
import android.app.Dialog
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ToastUtils
import com.htxcsoft.corelibrary.glide.GlideUtils
import com.junlong0716.enjoylearning.CommentPresenter
import com.junlong0716.enjoylearning.MyApp
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.constant.NetConstant
import com.junlong0716.enjoylearning.dialog.LoadingDialog
import com.junlong0716.enjoylearning.entity.rxevent.RefreshAvatarEvent
import com.junlong0716.enjoylearning.manager.MatisseGlideManager
import com.junlong0716.enjoylearning.net.api.NetApi
import com.junlong0716.module.common.rxbus.RxBus
import com.junlong0716.module.common.utils.Uri2PathUtils
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Progress
import com.lzy.okgo.model.Response
import com.tbruyelle.rxpermissions2.RxPermissions
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import kotlinx.android.synthetic.main.activity_user_info.*
import kotlinx.android.synthetic.main.view_title_bar.*
import org.json.JSONObject

class UserInfoActivity : AppCompatActivity() {
    private val REQUEST_CODE_CHOOSE = 0xffaf
    private lateinit var loadingDialog: LoadingDialog
    private var isGranted = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_user_info)

        GlideUtils.showImage(this, NetConstant.REQUEST_SOURCE + MyApp.instance().userAccount!!.headImg, civ_avatar, R.mipmap.ic_avatar_man)
        tv_phone.text = MyApp.instance().userAccount!!.userAccount
        tv_user_name.text = MyApp.instance().userAccount!!.userName
        fl_modify_avatar.setOnClickListener {

            requestPermission()

            Matisse.from(this)
                    .choose(MimeType.allOf())
                    .countable(true)
                    .maxSelectable(1)
                    //.addFilter(GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                    .gridExpectedSize(resources.getDimensionPixelSize(R.dimen.grid_expected_size))
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    .thumbnailScale(0.85f)
                    .imageEngine(MatisseGlideManager())
                    .forResult(REQUEST_CODE_CHOOSE)
        }


        rl_back.setOnClickListener {
            finish()
        }

    }

    private fun requestPermission() {
        val rxPermissions = RxPermissions(this)
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe { granted ->
                    if (granted) {
                        isGranted = true
                    } else {
                        ToastUtils.showShort("请允许获取权限！")
                        isGranted = false
                    }
                }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            val obtainResult = Matisse.obtainResult(data)
            if (!obtainResult.isEmpty()) {
                loadingDialog = LoadingDialog(this)
                loadingDialog.show()
                val photoPathFromContentUri = Uri2PathUtils.getPhotoPathFromContentUri(this, obtainResult[0])
                requestUploadFile(photoPathFromContentUri)
            }
        }
    }

    private fun requestUploadFile(photoPathFromContentUri: String) {
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_UPLOAD_FILE)
                .tag(this)
                .params("file", FileUtils.getFileByPath(photoPathFromContentUri))
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObj = JSONObject(response!!.body())
                        val code = jsonObj.getString("code")
                        if (code == "200") {
                            val filePath = jsonObj.getString("data")
                            requestUploadAvatar(filePath)
                        } else {
                            ToastUtils.showShort("上传头像失败")
                        }
                    }

                    override fun uploadProgress(progress: Progress?) {
                        loadingDialog.setProgress("图片上传中\n${(progress!!.fraction * 100).toInt()}%")
                    }

                    override fun onError(response: Response<String>?) {
                        ToastUtils.showShort("上传头像失败")
                    }
                })
    }

    private fun requestUploadAvatar(filePath: String?) {
        val map = HashMap<String, Any>()
        map["id"] = MyApp.instance().userAccount!!.id
        map["headImg"] = filePath!!
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_MODIFY_AVATAR)
                .tag(this)
                .upJson(JSONObject(map))
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObject = JSONObject(response!!.body())
                        val code = jsonObject.getString("code")
                        if (code == "200") {
                            loadingDialog.dismiss()
                            ToastUtils.showShort("上传头像成功！")
                            val commentPresenter = CommentPresenter()
                            commentPresenter.requestMyInfo(this@UserInfoActivity, object : CommentPresenter.UserInfoCallback {
                                override fun reqeustUserInfoSucceed(headImg: String) {
                                    RxBus.getDefault().post(RefreshAvatarEvent())
                                    GlideUtils.showImage(this@UserInfoActivity, NetConstant.REQUEST_SOURCE + headImg, civ_avatar, R.mipmap.ic_avatar_man)
                                }
                            })
                        }
                    }
                })
    }
}
